﻿using StudentLive.Common;
using StudentLive.DataModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;


// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace StudentLive.InnerPages
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class LessonDetails : StudentLive.Common.LayoutAwarePage
    {
        public LessonDetails()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {

            var coursePlanItem = LiveDataSource.GetCoursePlan((int)(navigationParameter));
            this.DataContext = coursePlanItem;
            this.DefaultViewModel["Items"] = coursePlanItem.Units;
            this.DefaultViewModel["SnappedItems"] = LiveDataSource.GetAllItemsOfCoursePlan(coursePlanItem.CoursePlanID);
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private void itemListView_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (this.unitsListView.SelectedItem != null)
            {
                var unitItem = (UnitItem)this.unitsListView.SelectedItem;
                lessonsListView.ItemsSource = unitItem.Lessons;
                this.lessonsListView.SelectedItem = lessonsListView.Items[0];
            }
        }

        private void lessonsListView_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (this.lessonsListView.SelectedItem != null)
            {
                var lessonItem = (LessonPlanItem)this.lessonsListView.SelectedItem;
                resourcesGridView.ItemsSource = lessonItem.Resources;
            }
        }

        private void resourcesGridView_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {

            var resourceItem = (ResourceItem)resourcesGridView.SelectedItem;
            if (resourceItem != null)
            {
                BottomAppBar.Visibility = Visibility.Visible;
                BottomAppBar.IsOpen = true;
                if (resourceItem.IsDownloaded == true)
                {
                    OpenButton.Visibility = Visibility.Visible;
                    DownloadButton.Visibility = Visibility.Collapsed;
                    if (resourceItem.IsFavoured)
                    {
                        FavoriteButton.Visibility = Visibility.Collapsed;
                        UnFavorButton.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        FavoriteButton.Visibility = Visibility.Visible;
                        UnFavorButton.Visibility = Visibility.Collapsed;
                    }
                }
                else
                {
                    OpenButton.Visibility = Visibility.Collapsed;
                    DownloadButton.Visibility = Visibility.Visible;
                    UnFavorButton.Visibility = Visibility.Collapsed;
                    FavoriteButton.Visibility = Visibility.Collapsed;
                }
            }
            else
                BottomAppBar.Visibility = Visibility.Collapsed;


        }

        private async void OnDownloadButtonClicked(object sender, RoutedEventArgs e)
        {
            var item = (ResourceItem)resourcesGridView.SelectedItem;
            StackPanel panel = (sender as Button).Parent as StackPanel;
            startLoadingWithParent(panel);
            await LiveDataSource.DownloadResource(item);
            stopLoadingWithParent(panel);
            OpenButton.Visibility = Visibility.Visible;
            FavoriteButton.Visibility = Visibility.Visible;
            DownloadButton.Visibility = Visibility.Collapsed;
            FavoriteButton.Visibility = Visibility.Visible;
        }

        private void OnOpenButtonClicked(object sender, RoutedEventArgs e)
        {
            var item = (ResourceItem)resourcesGridView.SelectedItem;
            if (item.IsDownloaded)
                DefaultLaunch(item.LocalPath);
        }

        private void FavoriteButtonClick(object sender, RoutedEventArgs e)
        {
            ResourceItem learningResource = null;
            if (resourcesGridView.SelectedItem != null)
            {
                learningResource = ((ResourceItem)(resourcesGridView.SelectedItem));
            }
            else if (itemListView.SelectedItem != null)
            {
                learningResource = ((ResourceItem)(itemListView.SelectedItem));
            }
            learningResource.IsFavoured = !learningResource.IsFavoured;
            LiveDataSource.UpdateLearningResource(learningResource);
            if (learningResource.IsFavoured)
            {
                UnFavorButton.Visibility = Visibility.Visible;
                FavoriteButton.Visibility = Visibility.Collapsed;
            }
            else
            {
                UnFavorButton.Visibility = Visibility.Collapsed;
                FavoriteButton.Visibility = Visibility.Visible;
            }
        }




        async void DefaultLaunch(string path)
        {
            // Path to the file in the app package to launch

            var file = await StorageFile.GetFileFromPathAsync(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, path));

            if (file != null)
            {
                // Set the option to show the picker
                //var options = new Windows.System.LauncherOptions();
                //options.DisplayApplicationPicker = true;

                // Launch the retrieved file
                bool success = await Windows.System.Launcher.LaunchFileAsync(file);
                if (success)
                {
                    // File launched
                }
                else
                {
                    // File launch failed
                }
            }
            else
            {
                // Could not find file
            }
        }

        void startLoadingWithParent(StackPanel parent)
        {
            ProgressBar bar = new ProgressBar();
            bar.IsIndeterminate = true;
            bar.Margin = new Thickness(0, 10, 0, 0);
            bar.Width = parent.Width;
            parent.Children.Insert(2, bar);
        }

        void stopLoadingWithParent(StackPanel parent)
        {
            foreach (var item in parent.Children)
            {
                if ((item as ProgressBar) != null)
                {
                    parent.Children.Remove(item);
                }
            }
        }

        private void resourcesGridView_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            if (e.ClickedItem.GetType() == typeof(LessonPlanItem))
            {
                return;
            }
            var resourceItem = (ResourceItem)e.ClickedItem;

            this.resourcesGridView.SelectedItem = resourceItem;

            if (resourceItem != null)
            {
                BottomAppBar.Visibility = Visibility.Visible;
                BottomAppBar.IsOpen = true;
                if (resourceItem.IsDownloaded == true)
                {
                    OpenButton.Visibility = Visibility.Visible;
                    DownloadButton.Visibility = Visibility.Collapsed;
                    if (resourceItem.IsFavoured)
                    {
                        FavoriteButton.Visibility = Visibility.Collapsed;
                        UnFavorButton.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        FavoriteButton.Visibility = Visibility.Visible;
                        UnFavorButton.Visibility = Visibility.Collapsed;
                    }
                }
                else
                {
                    OpenButton.Visibility = Visibility.Collapsed;
                    DownloadButton.Visibility = Visibility.Visible;
                    UnFavorButton.Visibility = Visibility.Collapsed;
                    FavoriteButton.Visibility = Visibility.Collapsed;
                }
            }
            else
                BottomAppBar.Visibility = Visibility.Collapsed;


        }
        //{
        //    this.BottomAppBar.IsOpen = true;
        //    //var resourceItem = (ResourceItem)e.ClickedItem;
        //    //if (resourceItem.IsDownloaded)
        //    //    DefaultLaunch(resourceItem.LocalPath);
        //}

        private async void DownloadButtonClick(object sender, RoutedEventArgs e)
        {

            StackPanel panel = (sender as Button).Parent as StackPanel;
            startLoadingWithParent(panel);
            await LiveDataSource.DownloadResource((ResourceItem)((Button)sender).Tag);
            stopLoadingWithParent(panel);

        }

        private void Unit_Header_Click_1(object sender, RoutedEventArgs e)
        {
            StudentLive.DataModel.HubGroups.UnitGroupContent unit = (sender as Button).DataContext as StudentLive.DataModel.HubGroups.UnitGroupContent;
            bool collapsed = unit.IsCollapsed;
            if (collapsed)
            {
                foreach (var item in unit.Items)
                {
                    unit.MirroredItems.Add(item);
                }
                unit.IsCollapsed = false;
            }
            else
            {
                unit.MirroredItems.Clear();
                unit.IsCollapsed = true;
            }
        }

        private void resourcesGridView_RightTapped_1(object sender, RightTappedRoutedEventArgs e)
        {
            resourcesGridView.Visibility = Visibility.Collapsed;
        }

        private void itemListView_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            if (e.ClickedItem.GetType() == typeof(LessonPlanItem))
            {
                return;
            }
            itemListView.SelectedItem = e.ClickedItem;

        }

        private void itemListView_SelectionChanged_2(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Last().GetType() == typeof(LessonPlanItem))
            {
                return;
            }
            var resourceItem = (ResourceItem)e.AddedItems.Last();
            if (resourceItem != null)
            {
                BottomAppBar.Visibility = Visibility.Visible;
                BottomAppBar.IsOpen = true;
                if (resourceItem.IsDownloaded == true)
                {
                    OpenButton.Visibility = Visibility.Visible;
                    DownloadButton.Visibility = Visibility.Collapsed;
                    if (resourceItem.IsFavoured)
                    {
                        FavoriteButton.Visibility = Visibility.Collapsed;
                        UnFavorButton.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        FavoriteButton.Visibility = Visibility.Visible;
                        UnFavorButton.Visibility = Visibility.Collapsed;
                    }
                }
                else
                {
                    OpenButton.Visibility = Visibility.Collapsed;
                    DownloadButton.Visibility = Visibility.Visible;
                    UnFavorButton.Visibility = Visibility.Collapsed;
                    FavoriteButton.Visibility = Visibility.Collapsed;
                }
            }
            else
                BottomAppBar.Visibility = Visibility.Collapsed;
        }


    }
}
